package com.tako.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.PropertyResourceBundle;
import java.util.function.Consumer;

/**
 * @author zhangyu
 * @date 2022/7/30
 */
public class FileUtil {

    private FileUtil() {
    }

    public static String[] getFileNamePart(File file) {
        String name = file.getName();
        int i = name.lastIndexOf(".");
        if (i == 0 || i == name.length()) {
            throw new IllegalArgumentException("file name: " + name);
        }
        return new String[]{name.substring(0, i), name.substring(i + 1)};
    }

    public static String getDesktopPath(String fileName) {
        return System.getProperty("user.home") + File.separator + "Desktop" + File.separator + fileName;
    }

    public static File getDesktopFile(String fileName) {
        String path = getDesktopPath(fileName);
        return Paths.get(path).toFile();
    }

    public static File createDeskTopFile(String fileName) throws IOException {
        File file = getDesktopFile(fileName);
        if (file.isDirectory()) {
            throw new RuntimeException("请输入文件名");
        }
        File parentFile = file.getParentFile();
        parentFile.mkdirs();
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        return file;
    }

    public static File validateAndCreateDesktopFolder(String folderName) {
        File file = getDesktopFile(folderName + File.separator);
        if (file.exists() && !file.isDirectory()) {
            throw new RuntimeException("folderName非文件夹");
        } else {
            file.mkdirs();
        }
        return file;
    }

    public static void readFileByLine(File file, Consumer<String> consumer) throws IOException {
        try (FileReader fileReader = new FileReader(file);
             BufferedReader bufferedReader = new BufferedReader(fileReader)) {
            // 读取文件
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                consumer.accept(line);
            }
        } catch (Exception e) {
            throw e;
        }
    }

    public static void saveStringFile(File file, String content) throws IOException {
        try (FileWriter fileWriter = new FileWriter(file);
             BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
            bufferedWriter.write(content);
        } catch (Exception e) {
            throw e;
        }
    }
}
